#!/bin/sh

appdir=/opt/toughadmin
rundir=/var/toughadmin

usage ()
{
        cat <<EOF
Usage: $0 [OPTIONS]
  start              start toughradius
  stop               stop toughradius
  restart            restart toughradius
  status             show toughradius run status
  upgrade            update toughradius version and restart

All other options are passed to the toughrad program.
EOF
        exit 1
}

# support docker start
start()
{
    if [ ! -d ${rundir} ]; then
        mkdir -p ${rundir}/data
        mkdir -p ${rundir}/log
    fi


     # toughradius not running, start it
    if [ ! $( pgrep -f supervisord | wc -l ) -gt 0 ]
    then
        supervisord -n -c /etc/supervisord.conf
    fi
}

# support docker
stop()
{
    if [ $( pgrep -f supervisord | wc -l ) -gt 0 ]
    then
        supervisorctl stop all
        supervisorctl shutdown
    else
        echo "supervisord not running"
    fi
}

# support docker
status()
{
    if [ $( pgrep -f supervisord | wc -l ) -gt 0 ]
    then
        supervisorctl status
    else
        echo "supervisord not running"
    fi

}

# not support docker
restart()
{
    if [ $( pgrep -f supervisord | wc -l ) -gt 0 ]
    then
        supervisorctl restart all
    else
        supervisord -c /etc/supervisord.conf
    fi
}

# support docker
upgrade()
{
    echo 'starting upgrade...'

    cd ${appdir} && git checkout master && git pull origin master
    supervisorctl restart all
    supervisorctl status
    echo 'upgrade done'
}


case "$1" in

  start)
    start
  ;;

  stop)
    stop
  ;;

  status)
    status
  ;;

  restart)
    restart
  ;;

  upgrade)
    upgrade
  ;;

  *)
   usage
  ;;

esac